import { createRouteMap } from "./creater-route-map";

export const createRoute = (record, { path }) => {
  let matched = [];
  if (record){
    while (record) { // 如果已经存在记录就将自己插入到队列的头部
      matched.unshift(record);
      record = record.parent; // 一层层的向上找
    }
  }
  return {
    path,
    matched
  }
}

export function createMatcher(routes) { // 树形的路由扁平化，匹配器
  const { pathMap } = createRouteMap(routes); // 创建一个 路径和记录的映射表
  
  /**
   * 动态添加路由
   * @param {Array} routes 
   */
  const addRoutes = routes => {
    createRouteMap(routes, pathMap);
  }
  // addRoutes([
  //   {
  //     path: '/about',
  //     children: [
  //       {
  //         path: 'c'
  //       }
  //     ]
  //   }
  // ])
   /**
   * 根据路径匹配组件
   * {path: '/about/a', matched:['about 组件', 'a 组件']}
   * @param {*} location 
   */
  const match = location => {
    const record = pathMap[location]; // 根据路径找到其对应的数据, 
    if (record) {
      return createRoute(record, {path: location});
    }
    return createRoute(null, {path: location});
  }
  
  // console.log(match('/about/a'))
  return {
    addRoutes,
    match
  }
}